<template>
  <div class="add-payslip">
    <a-button icon="left" type="link" style="color:#D8D8D8;margin-left:-12px" @click="$router.go(-1)">返回</a-button>
    <div class="addPayslip-middle">
      <a-row class="content-con">
        <div style="display: flex;justify-content: center;">
          <img :src="require('@/assets/img/wageMonthFile.png')" style="width: 24px;height: 24px;position: relative;right: 10px;top: 5px" />
          <h2 class="title">上传历史工资表</h2>
        </div>
        <a-form layout="inline" class="form" :form="form">
          <a-row>
            <a-form-item class="form-item" label="请选择月份">
              <a-month-picker format="YYYY-MM" style="width:300px" placeholder="请选择" v-model="selectDate" />
            </a-form-item>
          </a-row>
          <a-row>
            <a-form-item class="form-item" label="工资表名称">
              <a-input placeholder="请输入" style="width:300px" :max-length="20" v-model="tableName" />
            </a-form-item>
          </a-row>
          <a-form-item>
            <a-upload :action="action" @change="cbUpload">
              <a-button @click="onUpload" type="primary" :disabled="disabled">
                导入月工资表
              </a-button>
            </a-upload>
          </a-form-item>
        </a-form>
      </a-row>
      <a-row class="content-foot">
        <h3>导入提示</h3>
        <div class="sub_tit">
          1、上传的月工资表，需要提供以下信息：
        </div>
        <div class="sub_tit">
          员工姓名、手机号、定薪工资、应发工资、社保金个人缴纳、公积金个人缴纳、个人所得税、实发工资；
        </div>
        <div class="sub_tit">
          2、如上传遇到问题，请使用标准模版上传
          <span class="primary">
            <a @click="download">「历史工资上传模板」</a>
          </span>
        </div>
        <div class="sub_tit">
          3、暂不支持复合表头（即合并单元格）；
        </div>
        <div class="sub_tit">
          4、上传的员工必须存在于员工花名册中，否则系统无法识别
        </div>
      </a-row>
    </div>
  </div>
</template>

<script>
import { mapState, mapMutations, mapGetters } from "vuex";
import { importPayroll } from "@/api/wages/monthly";
import axios from "axios";
import qs from "qs";
export default {
  name: "AddPayslip",

  data() {
    return {
      inputText: "",
      selectDate: undefined,
      tableName: "",
      action: "",
      columns: [
        {
          key: "empName",
          title: "姓名",
          width: 150,
          dataIndex: "empName",
          fixed: "left"
        },
        {
          title: "企业员工",
          key: "empInCompany",
          dataIndex: "empInCompany",
          width: 150,
          scopedSlots: { customRender: "empInCompany" }
        },
        {
          title: "手机",
          dataIndex: "phoneStatus",
          key: "phoneStatus",
          width: 150,
          scopedSlots: { customRender: "phoneStatus" }
        },
        {
          title: "微信",
          dataIndex: "wechatStatus",
          key: "wechatStatus",

          width: 150,
          scopedSlots: { customRender: "wechatStatus" }
        },
        {
          title: "手机号",
          dataIndex: "phone",
          key: "phone",

          width: 150
        },
        {
          title: "基本工资",
          dataIndex: "salaryBasic",
          key: "salaryBasic",

          width: 150
        },
        {
          title: "个人社保",
          dataIndex: "empSoc",
          key: "empSoc",
          width: 150
        },
        {
          title: "实发工资",
          dataIndex: "salaryReal",
          key: "salaryReal",
          width: 150
        }
      ],
      titles: {},
      cbParams: {
        pageNo: 1,
        reloadCount: true,
        pageSize: 10
      },
      pagination: {
        pageSize: 10,
        current: 1,
        total: 0
      },
      salary: [],
      excelVisible: false,
      excelOptions: {},
      hide: false,
      form: this.$form.createForm(this, { name: "coordinated" }),
      params: {
        month: "",
        year: "",
        tableName: ""
      },
      tableId: ""
    };
  },
  computed: {
    ...mapState(["hr"]),
    ...mapGetters({ PAYSLIP: "wages/PAYSLIP" }),
    disabled() {
      return !(this.tableName !== "" && this.selectDate !== undefined);
    }
  },

  methods: {
    monthChange(e) {},
    ...mapMutations({
      getSuccessList: "wages/successList",
      cbData: "wages/cbData",
      tableIds: "wages/tableId",
      postParams: "wages/postParams",
      resetPostParams: "wages/resetPostParams"
    }),
    // 导入工资表
    onUpload() {
      const [year, month] = this.selectDate.format("YYYY-MM").split("-");
      this.action = `/salary/api/v1/employeeSalaries/import?companyId=${this.hr.companyId}&month=${month}&year=${year}&salaryTemplateName=${this.tableName}`;
      this.params.year = year;
      this.params.month = month;
    },
    cbUpload(e) {
      if (e.file) {
        if (e.file.response && e.file.response.data) {
          const data = e.file.response.data;
          this.tableId = data.tableId;
          const { response } = e.file;
          if (response && response.data && response.data) {
            // this.onUploadChange(response.data);
            this.$notification["success"]({
              message: "success",
              description: "上传成功"
            });
            this.$router.go(-1);
          }
        } else {
          if (e.file.response && e.file.response.msg) {
            this.$notification["error"]({ message: e.file.response.msg });
          }
        }
      }
    },
    onUploadChange(data) {
      this.excelVisible = true;
      this.excelOptions = data;
      this.tableId = data.tableId;
    },
    // 上传成功的excel
    successExcel() {
      this.$request({
        url: `/hr/api/v1/salaryBills/pageRelation`,
        params: {
          companyId: this.hr.companyId,
          tableId: this.tableId,
          ...this.cbParams,
          pageSize: this.pagination.pageSize
        }
      }).then(({ data }) => {
        //  this.cbData(data);
        this.titles = {
          countAll: data.countAll,
          countInCompany: data.countInCompany,
          countNotInCompany: data.countNotInCompany,
          countWeChatBind: data.countWeChatBind,
          countWeChatUnBind: data.countWeChatUnBind,
          sumSalaryAmount: data.sumSalaryAmount,
          sumSalaryReal: data.sumSalaryReal
        };
        this.salary = data.salaryBillListVOPage.entities || [];
        // this.getSuccessList(this.salary);
        this.pagination.total = data.salaryBillListVOPage.entityCount || 0;
        this.salary.forEach(item => {
          item.salaryBillFieldsDOList.forEach(key => {
            key.dataIndex = key.sort;
          });
        });
        const colum = [];
        this.salary[0].salaryBillFieldsDOList.map(key => {
          colum.push({
            dataIndex: key.sort,
            title: key.fieldName,
            width: 150,
            key: key.sort
          });
        });
        this.salary = this.salary.map(item => {
          const obj = {};
          item.salaryBillFieldsDOList.map(key => {
            obj[key["dataIndex"]] = key["fieldValue"];
          });
          item = { ...item, ...obj };
          return item;
        });
        this.columns = [...this.columns, ...colum];
      });
    },
    // excelCalback
    excelChange(e) {
      if (e.visibleWrong) {
        this.excelVisible = e.visibleWrong;
      } else {
        this.excelVisible = false;
        this.$router.push({
          path: "add-payslip-sort",
          query: {
            tableId: this.tableId,
            month: this.params.month,
            year: this.params.year,
            sendName: this.tableName
          }
        });
      }
    },
    // 下载模板
    download() {
      const token = this.$store.state.auth.token;
      let params = {};
      params = {
        templateName: "recordSalaryUpload.xlsx"
      };

      axios({
        url: ` /salary/api/v1/excel/template/download`,
        params,
        paramsSerializer: param => {
          return qs.stringify(param, { indices: false });
        },
        method: "get",
        responseType: "blob",
        headers: {
          token: token
        }
      })
        .then(res => {
          const link = document.createElement("a");
          const blob = new Blob([res.data], {
            type: "multipart/form-data"
          });
          link.style.display = "none";
          link.href = URL.createObjectURL(blob);
          link.setAttribute("download", "历史工资上传模板.xlsx");
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        })
        .catch(err => {
          console.log("debug log --> ", err);
        });
    },
    // 表单提交
    handleSubmit(e) {
      this.form.validateFields((err, values) => {
        if (!err) {
          values.selectDate = values.selectDate.format("YYYY-MM");
          this.params.tableName = values.tableName;
          this.params.year = values.selectDate.split("-")[0];
          this.params.month = values.selectDate.split("-")[1];
          this.hide = !this.hide;
          this.postParams({
            sendName: values.tableName,
            month: this.params.month,
            year: this.params.year
          });
        }
      });
    },
    // 重新上传
    reUpload() {
      this.salary = [];
      this.tableName = "";
      this.selectDate = undefined;
    },

    // 翻页
    handlePage(e) {
      this.pagination.current = e.current;
      this.cbParams.pageNo = e.current;

      this.$request({
        url: `/hr/api/v1/salaryBills/pageRelation`,
        params: {
          companyId: this.hr.companyId,
          tableId: this.tableId,
          ...this.cbParams
        }
      }).then(({ data }) => {
        this.titles = {
          countAll: data.countAll,
          countInCompany: data.countInCompany,
          countNotInCompany: data.countNotInCompany,
          countWeChatBind: data.countWeChatBind,
          countWeChatUnBind: data.countWeChatUnBind,
          sumSalaryAmount: data.sumSalaryAmount,
          sumSalaryReal: data.sumSalaryReal
        };
        this.salary = data.salaryBillListVOPage.entities || [];
        this.pagination.total = data.salaryBillListVOPage.entityCount || 0;
        this.getSuccessList(this.salary);
      });
    },

    // 下一页
    next() {
      this.$router.push({
        path: "/wages/add-payslip-second",
        query: {
          unSendCount: this.pagination.total
        }
      });
    },
    // 筛选
    selectItem(type) {}
  }
};
</script>
<style lang="scss" scoped>
.add-payslip {
  padding: 24px;
  .addPayslip-middle {
    .content-con {
      background-image: url(~@/assets/img/wageMonthBg.png);
      background-size: 100% 100%;
    }
  }
  .content-top {
    margin-top: 24px;
    padding: 40px 162px;
    background: #fafafa;
    border-radius: 4px;
  }
  .content-con {
    text-align: center;
    margin-top: 24px;
    padding: 40px 162px;
    background: #ffffff;
    box-shadow: 0px 4px 12px 0px var(--primary10);
    border-radius: 4px;
    ::v-deep.form {
      text-align: center;
      .form-item {
        margin: 12px 0;
        text-align: left;
      }
    }
  }
  .content-foot {
    margin-top: 24px;
    padding: 24px;
    background: #fafafa;
    border-radius: 4px;
  }
  .salary {
    cursor: pointer;
    margin: 24px 0;
    .item {
      padding: 24px;
      text-align: center;
      border: 1px solid #ccc;
      border-radius: 4px;
    }
  }
}
</style>
